/**
 * 公用工具函数
 */

// 转换为树形结构
export const listToTree = (list: any[], key ='id') => {
    let info = list.reduce((map, node) => (map[node[key]] = node, node.children = [], map), {})
    return list.filter(node => {
        info[node.parentId] && info[node.parentId].children.push(node)
        return !node.parentId
    })
}

// 平铺tree结构数据
export const unfoldTreeList = (list: any[] = [], childrenName: string[], childrenIgnore?: any, arr: any[] = []) => {
    let key: string;
    let value: any;
    if (typeof childrenIgnore === 'object') {
        key = childrenIgnore.key;
        value = childrenIgnore.value;
    }
    list = list || [];
    list.forEach(item => {
        let obj = {...item};
        let children;
        if (childrenName instanceof Array) {
            childrenName.forEach(name => {
                if (obj[name] instanceof Array) {
                    delete obj[name];
                    children = item[name];
                }
            });
        } else {
            if (item[key] !== value) {
                delete obj[childrenName];
            }
            children = item[childrenName];
        }
        arr.push(obj);
        if (children instanceof Array && (!key || (item[key] !== value))) {
            unfoldTreeList(children, childrenName, childrenIgnore, arr);
        }
    });
    return arr;
}

// 删除左右两端的空格
export const trim = (str: string) => {
    return str.replace(/(^\s*)|(\s*$)/g, '');
}
